package com.lenovo.leos.letools.db;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.lenovo.leos.letools.utils.Constants;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class FileUploadService {

	private DBOpenHelper openHelper;
	
	/** 表中字段isloading对应的值 **/
	public static final int isloading_no = 0;
	public static final int isloading_yes = 1;
	
	public FileUploadService(Context context) {
		openHelper = new DBOpenHelper(context);
	}
	
	/**
	 * 创建一个任务
	 * @param wholePath
	 * @param startIndex
	 * @param filelen
	 * @param fileid 上传文件在服务器端生成的id
	 * @param parentDirId  文件上传到服务器端的目录id
	 * @param localTopDirWholePath 上传文件夹时用到   本地上传文件夹的顶层全路径  上传一般文件时为null
	 */
	public void save(String wholePath,int filelen,String fileid,
			String parentDirId,String localTopDirWholePath,String cookie_token,String uploadUrl) {
		SQLiteDatabase db = openHelper.getWritableDatabase();
		db.beginTransaction();
		String sql = "insert into fileuplog(wholePath,startIndex,filelen,fileState,fileid,parentDirId,localTopDirWholePath,cookie_token,isloading,uploadUrl) values(?,?,?,?,?,?,?,?,?,?)";
		try{
			db.execSQL(sql,new Object[]{wholePath,0,filelen,Constants.loadover_no,fileid,parentDirId,localTopDirWholePath,cookie_token,Constants.isloading_yes,uploadUrl});
			db.setTransactionSuccessful();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			db.endTransaction();
			db.close();
		}
	}
	/**
	 * 更改上传文件的状态
	 * 
	 * @param path
	 *            isloading_no 未下载；isloading_yes正在下载
	 */
	public void updateIsLoading(String wholePath, int isloadingVal) {
		String sql = "update fileuplog set isloading =? where wholePath=?";
		SQLiteDatabase db = openHelper.getWritableDatabase();
		db.beginTransaction();
		try {
			db.execSQL(sql, new Object[] {isloadingVal,wholePath});
			db.setTransactionSuccessful();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			db.endTransaction();
		}
		db.close();
	}
	/**
	 * 实时更新 断点
	 * @param wholePath
	 * @param startIndex
	 */
	public void updateBlockPosition(String wholePath,int startIndex){
		String sql = "update fileuplog set startIndex=?,fileState=1 where wholePath=?";
		SQLiteDatabase db = openHelper.getWritableDatabase();
		db.beginTransaction();
		try{
			db.execSQL(sql,new Object[]{startIndex,wholePath});
			db.setTransactionSuccessful();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			db.endTransaction();
			db.close();
		}
	}
	/**
	 * 实时更新任务状态
	 * @param wholePath
	 * @param fileState
	 */
	public void updateFileState(String wholePath,int fileState){
		String sql = "update fileuplog set fileState=? where wholePath=?";
		SQLiteDatabase db = openHelper.getWritableDatabase();
		db.beginTransaction();
		try{
			db.execSQL(sql,new Object[]{fileState,wholePath});
			db.setTransactionSuccessful();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			db.endTransaction();
			db.close();
		}
	}
	/**
	 * 获得指定wholePath的文件任务信息
	 * 要续传的文件的startIndex和endIndex
	 * @param wholePath
	 * @return
	 */
	public FileUploadEntity getFileTaskByWholePath(String wholePath){
		FileUploadEntity fue = null;
		String sql = "select * from fileuplog where wholePath=?";
		SQLiteDatabase db = openHelper.getWritableDatabase();
		Cursor cursor = db.rawQuery(sql,new String[]{wholePath});
		if(cursor.moveToFirst()){
			fue = new FileUploadEntity();
			fue.setId(cursor.getInt(cursor.getColumnIndex("id")));
			fue.setWholePath(cursor.getString(cursor.getColumnIndex("wholePath")));
			fue.setStartIndex(cursor.getInt(cursor.getColumnIndex("startIndex")));
			fue.setFilelen(cursor.getInt(cursor.getColumnIndex("filelen")));
			fue.setFileState(cursor.getInt(cursor.getColumnIndex("fileState")));
			fue.setFileid(cursor.getString(cursor.getColumnIndex("fileid")));
			fue.setParentDirId(cursor.getString(cursor.getColumnIndex("parentDirId")));
			fue.setLocalTopDirWholePath(cursor.getString(cursor.getColumnIndex("localTopDirWholePath")));
			fue.setCookie_token(cursor.getString(cursor.getColumnIndex("cookie_token")));
			fue.setIsloading(cursor.getInt(cursor.getColumnIndex("isloading")));
			fue.setUploadUrl(cursor.getString(cursor.getColumnIndex("uploadUrl")));
		}
		cursor.close();
		db.close();
		return fue;
	}
	/**
	 * 获得所有文件上传的任务
	 * @return
	 */
	public List<FileUploadEntity> getAllFileTask(){
		String sql = "select * from fileuplog where localTopDirWholePath is null";
		List<FileUploadEntity> list = new ArrayList<FileUploadEntity>();
		SQLiteDatabase db = openHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery(sql,null);
		try{
			if(cursor.getCount()==0) return null;//没有记录返回null
			while(cursor.moveToNext()){
				FileUploadEntity fue = new FileUploadEntity();
				fue.setId(cursor.getInt(cursor.getColumnIndex("id")));
				fue.setWholePath(cursor.getString(cursor.getColumnIndex("wholePath")));
				fue.setStartIndex(cursor.getInt(cursor.getColumnIndex("startIndex")));
				fue.setFilelen(cursor.getInt(cursor.getColumnIndex("filelen")));
				fue.setFileState(cursor.getInt(cursor.getColumnIndex("fileState")));
				fue.setFileid(cursor.getString(cursor.getColumnIndex("fileid")));
				fue.setParentDirId(cursor.getString(cursor.getColumnIndex("parentDirId")));
				fue.setLocalTopDirWholePath(cursor.getString(cursor.getColumnIndex("localTopDirWholePath")));
				fue.setCookie_token(cursor.getString(cursor.getColumnIndex("cookie_token")));
				fue.setIsloading(cursor.getInt(cursor.getColumnIndex("isloading")));
				fue.setUploadUrl(cursor.getString(cursor.getColumnIndex("uploadUrl")));
				list.add(fue);
			}
		}finally{
			cursor.close();
			db.close();
		}
		return list;
	}
	/**
	 * 文件夹上传使用
	 * 获得同一个顶层目录下的所有任务信息
	 * @param dirWholePath
	 * @return
	 */
	public List<FileUploadEntity> getTasksPreTopDirWholePath(String localTopDirWholePath){
		List<FileUploadEntity> fues = null;
		
		String sql = "select * from fileuplog where localTopDirWholePath=?";
		SQLiteDatabase db = openHelper.getWritableDatabase();
		Cursor cursor = db.rawQuery(sql,new String[]{localTopDirWholePath});
		if(null != cursor && cursor.getCount() > 0){
			fues = new ArrayList<FileUploadEntity>();
		}
		while(cursor.moveToNext()){
			FileUploadEntity fue = new FileUploadEntity();
			fue.setId(cursor.getInt(cursor.getColumnIndex("id")));
			fue.setWholePath(cursor.getString(cursor.getColumnIndex("wholePath")));
			fue.setStartIndex(cursor.getInt(cursor.getColumnIndex("startIndex")));
			fue.setFilelen(cursor.getInt(cursor.getColumnIndex("filelen")));
			fue.setFileState(cursor.getInt(cursor.getColumnIndex("fileState")));
			fue.setFileid(cursor.getString(cursor.getColumnIndex("fileid")));
			fue.setParentDirId(cursor.getString(cursor.getColumnIndex("parentDirId")));
			fue.setLocalTopDirWholePath(cursor.getString(cursor.getColumnIndex("localTopDirWholePath")));
			fue.setCookie_token(cursor.getString(cursor.getColumnIndex("cookie_token")));
			fue.setIsloading(cursor.getInt(cursor.getColumnIndex("isloading")));
			fue.setUploadUrl(cursor.getString(cursor.getColumnIndex("uploadUrl")));
			fues.add(fue);
		}
		cursor.close();
		db.close();
		return fues;
	}
	/**
	 * 文件夹上传使用
	 * 获得所有文件夹任务信息 map中的key为localTopDirWholePath value为同一顶层目录下的所有文件任务
	 * @return
	 */
	public Map<String,List<FileUploadEntity>> getAllDirTask(){
		
		Map<String,List<FileUploadEntity>> dirTasks = new HashMap<String, List<FileUploadEntity>>();
		
		String sql = "select localTopDirWholePath from fileuplog group by localTopDirWholePath";
		SQLiteDatabase db = openHelper.getWritableDatabase();
		Cursor cursor = db.rawQuery(sql,new String[]{});
		while(cursor.moveToNext()){
			String localTopDirWholePath = cursor.getString(cursor.getColumnIndex("localTopDirWholePath"));
			if(localTopDirWholePath==null) continue;
			List<FileUploadEntity> fues = getTasksPreTopDirWholePath(localTopDirWholePath);
			dirTasks.put(localTopDirWholePath, fues);
		}
		cursor.close();
		db.close();
		return dirTasks;
	}
	
	/**
	 * 获得文件和文件夹的所有上传任务
	 * @return
	 */
	public AllUploadTaskEntity getFileAndDirAllTasks(){
		Map<String,List<FileUploadEntity>> dirTasks = getAllDirTask();
		List<FileUploadEntity> fileTasks = getAllFileTask();
		if(fileTasks==null) fileTasks = new ArrayList<FileUploadEntity>();
		return new AllUploadTaskEntity(fileTasks,dirTasks);
	}
	/**
	 * 删除一个文件上传任务
	 * @param wholePath
	 */
	public void deleteFileTask(String wholePath){
		String sql = "delete from fileuplog where wholePath=?";
		SQLiteDatabase db = openHelper.getReadableDatabase();
		db.execSQL(sql,new String[]{wholePath});
		db.close();
	}
	/**
	 * 删除一个文件夹上传任务
	 * @param wholePath
	 */
	public void deleteDirTask(String localTopDirWholePath){
		String sql = "delete from fileuplog where localTopDirWholePath=?";
		SQLiteDatabase db = openHelper.getReadableDatabase();
		db.execSQL(sql,new String[]{localTopDirWholePath});
		db.close();
	}
	
	/**
	 * 删除所有
	 */
	public void deleteAll(){
		String sql = "delete from fileuplog";
		SQLiteDatabase db = openHelper.getReadableDatabase();
		db.execSQL(sql);
		db.close();
	}
	
	//add by gaoge 2011-04-27 
	public String getParentRootPath(String filepath){
		String parentRootDir = null ;
		SQLiteDatabase db = openHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery(
				"select localTopDirWholePath from fileuplog where wholePath=?",
				new String[] { filepath });
		while (cursor.moveToNext()) {
			parentRootDir = cursor.getString(0);
		}
		cursor.close();
		db.close();
		return parentRootDir;
	}
}
